package vn.com.epi.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload-file.html")
@MultipartConfig
public class UploadFileServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    
    public UploadFileServlet() {
        super();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.getRequestDispatcher("/WEB-INF/jsp/upload-file-form.jsp").forward(request, response);
    }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        try {
            final String path = request.getParameter("destination");
            final Part filePart = request.getPart("file");
            final String fileName = getFileName(filePart);
            InputStream uploadedInputStream = filePart.getInputStream();
            String uploadedFileLocation = path + "/" + fileName;
            // save it
            String s = writeToFile(uploadedInputStream, uploadedFileLocation);
            String respond = "File uploaded to: " + uploadedFileLocation;
            if (s.compareTo("successful") == 0)
                request.setAttribute("respond", respond);
            else
                request.setAttribute("respond", s);
        } catch (Exception e) {
            request.setAttribute("respond", e.toString());
        } finally {            
            request.getRequestDispatcher("/WEB-INF/jsp/respond.jsp").forward(request, response);
        }
    }
    
    private String getFileName(final Part part) {
        for (String content : part.getHeader("content-disposition").split(";")) {
            if (content.trim().startsWith("filename")) {
                return content.substring(
                        content.indexOf('=') + 1).trim().replace("\"", "");
            }
        }
        return null;
    }

    // save uploaded file to new location
    private String writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
        try {
            OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
            int read = 0;
            byte[] bytes = new byte[1024];
 
            out = new FileOutputStream(new File(uploadedFileLocation));
            while ((read = uploadedInputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            out.flush();
            out.close();
            return "successful";
        } catch (IOException e) {
            return e.toString();
        }
    }
 
}
